package com.example.app.manager.c1;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.TextureView;

import com.example.app.manager.MediaRecorderManager;
import com.example.app.manager.OnCameraTakePictureBack;
import com.example.app.view.c1.PreviewC1View;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 相机管理 5.0 以下系统用
 * 1.Camera1Manager
 * 2.setTextureView OR setTextureView
 * 3.onInitCamera
 */
public class Camera1Manager extends Camera1Base {
    private SurfaceView surfaceView;
    private PreviewC1View textureView;
    //预设值：预览宽和高
    private int previewW, previewH;
    //屏幕方向 0,1,2,3
    private int direction;
    private int orientation;

    public Camera1Manager(Activity activity) {
        //只能获取：1 竖屏 2 横屏
        orientation = activity.getResources().getConfiguration().orientation;
        direction = activity.getWindowManager().getDefaultDisplay().getRotation();
        initCameraParameter(direction, activity);
    }

    public void setTextureView(SurfaceView surfaceView, int previewW, int previewH) {
        this.surfaceView = surfaceView;
        this.previewW = previewW;
        this.previewH = previewH;
    }

    public void setTextureView(PreviewC1View textureView) {
        this.textureView = textureView;
        this.previewW = textureView.getWidth();
        this.previewH = textureView.getHeight();
    }

    @Override
    public SurfaceView getSurfaceView() {
        return surfaceView;
    }

    @Override
    public TextureView getPreviewView() {
        return textureView;
    }

    @Override
    protected int[] getPreviewWH() {
        d("-----" + "previewW:" + previewW + " previewH:" + previewH);
        return new int[]{previewW, previewH};
    }

    public void onInitCamera() {
        isPictureProceed = false;
        initCamera();
       /* if (surfaceView != null) {
            setOrientation();
            return;
        }
        d("设置屏幕旋转");
        setOrientation();*/
       /* Camera.Size previewSize = getPreviewSize();
        if (previewSize == null) {
            d("设置屏幕旋转失败");
            return;
        }
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //横屏
            textureView.setAspectRatio(
                    previewSize.width, previewSize.height);
        } else {
            //竖屏
            textureView.setAspectRatio(
                    previewSize.height, previewSize.width);
        }
        textureView.configureTransform(previewW, previewH, previewSize);
        */
        d("设置屏幕旋转成功");
    }

    public void onCameraClose() {
        cameraClose();
    }

    //切换相机镜头
    public void setCameraSwitch() {
        isPictureProceed = false;
        if (getCameraCount() <= 1) {
            d("不支持 切换摄像头");
        }
        MediaRecorderManager.getInstance().setMediaWork(4);
        setCameraBackSwitchover();
        cameraClose();
        onInitCamera();
    }

    //重新预览
    public void setRecoverPreview() {
        isPictureProceed = false;
        setResetPreview();
    }

    //设置相机缩放
    public void setCameraZoom(MotionEvent event) {
        if (!isOpne()) {
            return;
        }
        if (isPictureProceed) {
            return;
        }
        onCameraZoom(event);
    }

    //设置相机聚焦
    public void setCameraFocus(int x, int y) {
        if (!isOpne()) {
            return;
        }
        if (isPictureProceed) {
            return;
        }
        onCameraFocus(x, y);
    }

    //设置开启相机灯光
    public void setCameraLight() {
        if (!isOpne()) {
            return;
        }
        isPictureProceed = false;
        onCameraSwithLight();
    }

    //拍照路径
    private String pathPicture;
    //true 拍照中
    private boolean isPictureRun;
    //true 拍照进行
    private boolean isPictureProceed;

    //获取拍照状态
    public boolean isPictureRun() {
        return isPictureRun;
    }

    /**
     * 拍照
     *
     * @param shutter
     * @param raw
     */
    public void onCameraTakePicture(String pathPicture, Camera.ShutterCallback shutter, Camera.PictureCallback raw) {
        if (!isOpne()) {
            return;
        }
        this.pathPicture = pathPicture;
        creatorFile(pathPicture);
        isPictureRun = true;
        isPictureProceed = true;
        d("拍照开始");
        //onCameraTake(shutter, previewCall, null);
        onCameraTake(shutter, null, onPictureCallback);
    }


    //开始录制视频
    public void onVideoStart(String videoPath) {
        onVideoStart(videoPath, -1);
    }

    public void onVideoStart(String videoPath, int endTime) {
        if (!isOpne()) {
            return;
        }
        creatorFile(videoPath);
        onCameraVideoStart(videoPath, endTime);
    }

    // 停止录制
    public void onVideoStop() {
        MediaRecorderManager.getInstance().setMediaWork(4);
    }

    //创建文件夹
    protected void creatorFile(String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        File file = new File(path);
        String p = file.getParent();
        File fileParent = new File(p);
        if (!fileParent.exists()) {
            boolean isOk = fileParent.mkdirs();
            d("创建文件夹" + isOk);
        }
    }

    private PreviewCall previewCall = new PreviewCall();

    //预览拍照？？
    class PreviewCall implements Camera.PreviewCallback {

        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {
            if (data == null || data.length <= 0) {
                Message msg = new Message();
                msg.obj = pathPicture;
                msg.what = 2;
                handlerCamera.sendMessage(msg);
                return;
            }
            // 保存图片
            final byte[] b = data;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //saveImageFile(b);
                    onSaveBitmap(b);
                }
            }).start();
        }
    }

    private OnPictureCallback onPictureCallback = new OnPictureCallback();

    //拍照
    class OnPictureCallback implements Camera.PictureCallback {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            if (data == null || data.length <= 0) {
                Message msg = new Message();
                msg.obj = pathPicture;
                msg.what = 2;
                handlerCamera.sendMessage(msg);
                return;
            }
            // 保存图片
            final byte[] b = data;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //saveImageFile(b);
                    onSaveBitmap(b);
                }
            }).start();
        }


    }

    /**
     * 处理拍照图片并保存
     *
     * @param data
     */
    private synchronized void onSaveBitmap(byte[] data) {
        // 保存图片
        Bitmap b = null;
        if (data.length != 0) {
            b = BitmapFactory.decodeByteArray(data, 0, data.length);
        }
        if (b == null) {
            d("照片data转Bitmap是失败");
            Message msg = new Message();
            msg.obj = pathPicture;
            msg.what = 2;
            handlerCamera.sendMessage(msg);
            return;
        }
        //一般前置设置头 90 后置摄像头 270
        int cameraOrientation = getCameraInfo().orientation;
        int orientation = 0;
        switch (cameraOrientation) {
            case 90:
                //前置摄像头
                orientation = 90;
                break;
            case 270:
                //一般是后置摄像头
                orientation = 270;
                break;
        }
        b = rotateBitmap(b, orientation);
        saveImageFile(b);
    }

    //直接写入照片比较快
    private void saveImageFile(byte[] data) {
        try {
            FileOutputStream out = new FileOutputStream(pathPicture);
            out.write(data);
            out.close();
            handlerCamera.sendEmptyMessage(1);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            d("写入照片失败：" + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            d("写入照片失败：" + e.getMessage());
        }
    }

    //写入照片 慢
    private void saveImageFile(Bitmap bmp) {
        File file = new File(pathPicture);
        Message msg = new Message();
        msg.obj = pathPicture;
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            msg.what = 1;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            d("写入照片失败：" + e.getMessage());
            msg.what = 2;
        } catch (IOException e) {
            e.printStackTrace();
            d("写入照片失败：" + e.getMessage());
            msg.what = 2;
        } finally {
            if (bmp != null && !bmp.isRecycled()) {
                bmp.recycle();
                bmp = null;
            }
        }
        if (handlerCamera == null) {
            d("拍照结束 但是不发送消息");
            return;
        }
        handlerCamera.sendMessage(msg);
        d("拍照结束");
    }

    private HandlerCamera handlerCamera = new HandlerCamera();

    /**
     * 旋转图片，使图片保持正确的方向。
     *
     * @param bitmap  原始图片
     * @param degrees 原始图片的角度
     * @return Bitmap 旋转后的图片
     */
    public Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
        if (degrees == 0 || null == bitmap) {
            return bitmap;
        }
        Matrix matrix = new Matrix();
        matrix.setRotate(degrees, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
        Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        bitmap.recycle();
        return bmp;
    }

    class HandlerCamera extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Object obj = msg.obj;
            switch (msg.what) {
                case 1:
                    isPictureRun = false;
                    String p = "";
                    if (obj != null && obj instanceof String) {
                        p = (String) obj;
                    }
                    onTakePictureBack(p, true);
                    d("拍照完成");
                    break;
                case 2:
                    isPictureRun = false;
                    startPreview();
                    p = "";
                    if (obj != null && obj instanceof String) {
                        p = (String) obj;
                    }
                    onTakePictureBack(p, false);
                    d("拍照失败");
                    break;
            }
        }
    }

    private void onTakePictureBack(String path, boolean isSucceed) {
        if (onCameraTakePictureBack == null) {
            return;
        }
        onCameraTakePictureBack.OnTakePictureBack(path, isSucceed);
    }

    //设置监听
    private OnCameraTakePictureBack onCameraTakePictureBack;

    private void setOnCameraTakePictureBack(OnCameraTakePictureBack onCameraTakePictureBack) {
        this.onCameraTakePictureBack = onCameraTakePictureBack;
    }
}
